package com.ksp.api.sqlscan;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;


public class DBConnImpl implements DBConn {
	
	private static final String DBDRIVER = "com.mysql.jdbc.Driver";
	private static final String DBURL = "jdbc:mysql://localhost:3306?characterEncoding=utf-8";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "111";
	 
	//连接池 最小连接数 最大连接数
	private static final int minCount = 1;
	private static final int maxCount = 10;
	private static final LinkedList<Connection> pools = new LinkedList<Connection>();

	//构建连接
	private Connection buildConnection() {
		Connection conn;
		try {
			Class.forName(DBDRIVER);
			conn = DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
			return conn;
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * @author xiaoD
	 * @date 2017年11月22日 下午2:49:38
	 * Description: 重写init
	 */
	public void init() {
		Connection conn = null;
		try{
			for(int i=0; i<minCount; i++) {
				conn = buildConnection();
				pools.add(conn);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @author xiaoD
	 * @date 2017年11月22日 下午2:49:38
	 * Description: 重写getConnection
	 */
	public synchronized Connection getConnection() {
		Connection conn = null;
		if(pools.size() == 0) {
			conn = buildConnection();
		} else {
			conn = pools.remove(0);
		}
		return conn;
	}

	/**
	 * @author xiaoD
	 * @date 2017年11月22日 下午2:49:38
	 * Description: 重写close
	 */
	public synchronized void close(Connection conn) {
		if(pools.size() < maxCount) {
			pools.add(conn);
		}
		//System.out.println(pools);
	}
}
